package com.bree.erp.service.stateless;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.Group;
import com.bree.erp.entity.GroupType;
import com.bree.erp.entity.Permission;
import com.bree.erp.entity.PermissionId;
import com.bree.erp.entity.Project;
import com.bree.erp.entity.User;
import com.bree.erp.service.GroupService;
import com.bree.erp.service.PermissionService;

@Stateless
public class PermissionServiceBean implements PermissionService {

	@PersistenceContext()
	private EntityManager em;
	
	@EJB
	private GroupService groupService;
	
	public PermissionServiceBean() {
		
	}

	public PermissionServiceBean(EntityManager em) {
		this.em = em;
	}
	
	@Override
	public Collection<Permission> list() {
		return null;
	}
	
	@Override
	public Permission create(String userId, Long projectId) {
		
		Set<GroupType> set = Collections.emptySet();
		
		return create(userId, projectId, set);
	}

	@Override
	public Permission create(String userId, Long projectId,
			Set<GroupType> groups) {
		
		Permission permission = new Permission();
		
		User user = em.find(User.class, userId);
		Project project = em.find(Project.class, projectId);
		
		permission.setUser(user);
		permission.setProject(project);
		permission.setGroups(groups);
		
		em.persist(permission);
		
		return permission;
	}

	@Override
	public Permission read(PermissionId id) {
		return em.find(Permission.class, id);
	}

	@Override
	public Permission update(PermissionId id, Set<GroupType> groups) {
		
		Permission entity = read(id);
		
		// TODO: Set<GroupType> oldGroups = entity.getGroups(); 
		
		entity.setGroups(groups);
		
		syncGroups(entity.getUser(), groups);
		
		return entity;
	}

	private void syncGroups(User user, Set<GroupType> groups) {
		
		for(GroupType groupType : groups) {
		
			Group group = groupService.read(user.getEmail(), groupType);
			if(group == null) {
				groupService.create(user, groupType);
			}
			
		}
		
	}

	@Override
	public void delete(PermissionId id) {
		
		Permission entity = read(id);
		
		em.remove(entity);
	}

	@Override
	public List<Project> listProjects(String email) {
		
		User user = em.find(User.class, email);

		TypedQuery<Project> query = em.createNamedQuery(Permission.QUERY_FIND_USERPROJECTS, Project.class)
				.setParameter("user", user)
				.setParameter("group", GroupType.USER);
		
		return query.getResultList();
	}

}
